<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人员类型" prop="personType">
        <el-select
          v-model="queryParams.personType"
          placeholder="请选择人员类型"
          clearable
          class="!w-240px"
        >
          <el-option label="考评员" :value="1" />
          <el-option label="监督员" :value="2" />
          <el-option label="工作人员" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="分配角色" prop="assignmentRole">
        <el-input
          v-model="queryParams.assignmentRole"
          placeholder="请输入分配角色"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分配状态" prop="assignmentStatus">
        <el-select
          v-model="queryParams.assignmentStatus"
          placeholder="请选择分配状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待确认" :value="0" />
          <el-option label="已确认" :value="1" />
          <el-option label="已取消" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:assignment:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="openBatchAssign"
          v-hasPermi="['eval:assignment:batch-assign']"
        >
          <Icon icon="ep:operation" class="mr-5px" /> 批量分配
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:assignment:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总分配数</div>
          </div>
          <Icon icon="ep:coordinate" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.pendingCount || 0 }}</div>
            <div class="text-gray-500">待确认</div>
          </div>
          <Icon icon="ep:clock" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.confirmedCount || 0 }}</div>
            <div class="text-gray-500">已确认</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ statistics.cancelledCount || 0 }}</div>
            <div class="text-gray-500">已取消</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评价计划" align="center" prop="planName" width="200" />
      <el-table-column label="人员姓名" align="center" prop="userName" width="120" />
      <el-table-column label="人员类型" align="center" prop="personType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_PERSON_TYPE" :value="scope.row.personType" />
        </template>
      </el-table-column>
      <el-table-column label="分配角色" align="center" prop="assignmentRole" width="120" />
      <el-table-column label="分配日期" align="center" prop="assignmentDate" width="120" />
      <el-table-column label="分配状态" align="center" prop="assignmentStatus" width="100">
        <template #default="scope">
          <el-tag :type="getAssignmentStatusTagType(scope.row.assignmentStatus)">
            {{ getAssignmentStatusText(scope.row.assignmentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分配说明" align="center" prop="assignmentComments" width="200" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:assignment:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:assignment:update']"
            v-if="scope.row.assignmentStatus === 0"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="confirm" v-if="scope.row.assignmentStatus === 0">
                  确认
                </el-dropdown-item>
                <el-dropdown-item command="cancel" v-if="scope.row.assignmentStatus < 2">
                  取消
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.assignmentStatus === 2">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AssignmentForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <AssignmentDetail ref="detailRef" />
  
  <!-- 批量分配弹窗 -->
  <BatchAssignForm ref="batchAssignRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalPersonnelAssignmentVO, 
  EvalPersonnelAssignmentPageReqVO, 
  getPersonnelAssignmentPage, 
  deletePersonnelAssignment, 
  exportPersonnelAssignment,
  confirmPersonnelAssignment,
  cancelPersonnelAssignment
} from '@/api/eval/assignment'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import AssignmentForm from './AssignmentForm.vue'
import AssignmentDetail from './AssignmentDetail.vue'
import BatchAssignForm from './BatchAssignForm.vue'

/** 人员分配 列表 */
defineOptions({ name: 'EvalAssignment' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalPersonnelAssignmentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const queryParams = reactive<EvalPersonnelAssignmentPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  personType: undefined,
  assignmentRole: undefined,
  assignmentStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getPersonnelAssignmentPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 计算统计数据
    calculateStatistics()
  } finally {
    loading.value = false
  }
}

/** 计算统计数据 */
const calculateStatistics = () => {
  const totalCount = list.value.length
  const pendingCount = list.value.filter(item => item.assignmentStatus === 0).length
  const confirmedCount = list.value.filter(item => item.assignmentStatus === 1).length
  const cancelledCount = list.value.filter(item => item.assignmentStatus === 2).length
  
  statistics.value = {
    totalCount,
    pendingCount,
    confirmedCount,
    cancelledCount
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 批量分配操作 */
const batchAssignRef = ref()
const openBatchAssign = () => {
  batchAssignRef.value.open()
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalPersonnelAssignmentVO) => {
  switch (command) {
    case 'confirm':
      await handleConfirm(row.id!)
      break
    case 'cancel':
      await handleCancel(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 确认分配 */
const handleConfirm = async (id: number) => {
  try {
    await confirmPersonnelAssignment(id)
    message.success('确认成功')
    await getList()
  } catch {}
}

/** 取消分配 */
const handleCancel = async (id: number) => {
  try {
    await message.confirm('确认取消该人员分配？')
    await cancelPersonnelAssignment(id)
    message.success('取消成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deletePersonnelAssignment(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportPersonnelAssignment(queryParams)
    download.excel(data, '人员分配.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分配状态标签类型 */
const getAssignmentStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return typeMap[status] || ''
}

/** 获取分配状态文本 */
const getAssignmentStatusText = (status: number) => {
  const textMap = { 0: '待确认', 1: '已确认', 2: '已取消' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取已发布和进行中的计划
    const publishedPlans = await getPlanListByStatus(3) // 已发布
    const inProgressPlans = await getPlanListByStatus(4) // 进行中
    planList.value = [...publishedPlans, ...inProgressPlans]
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
